<?php
class OrderCheckController extends Controller{
	public function __construct($data) {
		parent::__construct($data);
	}

	public $goodslist;//{array {'goodid','goodname','goodprice','goodnum'} ,array {'goodid','goodname','goodprice','goodnum'}}
	public $extraprice;//array{'buyingprice'=>10,'sendprice'=>20,'tax'=>30}
	public $sendinfo;//array{'orderpay'=>'orderpay1','ordersend'=>'ordersend1','sendcomment'->'sendcomment1'}
	public $cardinfo;//array{'cardno'=>'aaaaaaaaaaaaa','carddate'=>'2013-09'}
	public $addressinfo;//array{'sendname'=>'sendname1','sendnamef'=>'sendnamef','zipcode'=>'zipcode1','localname'=>'localname1','treetname'=>'treetname1','address'=>'address1','telno'=>'999-999-9999',officename'=>'officename1','officenamef'=>'officenamef1'}
	public $Registeraddressinfo;
	public $Userid;
	public function index(){

		try
		{
			require_once( '../system/ecjp_m.php' );
			
		   $this->_load_php_file("chklogin.php");
	        if(!isset($_SESSION['USER'])){
	    	
	       require_once( '../system/cookie.php' );
	    
	        }
			//load session
            $this->loaduser();
			if(!$this->loadsessiondata())
			{
				header('Location: pc_Top_index.html');return;
			}
			$allSumPrice=0;
			foreach( $this->goodslist as $value)
			{
				$allSumPrice+=(float)$value['goodprice']*$value['goodnum'];

			}

			$this->assign('good_data', $this->goodslist);
			$this->assign('allSumPrice', $allSumPrice);
			$this->assign('buyingprice',(float)$this->extraprice['buyingprice']);
			$this->assign('sendprice',(float)$this->extraprice['sendprice']);
			$this->assign('tax', (float)$this->extraprice['tax']);
			$this->assign('orderSumPrice',$allSumPrice+(float)$this->extraprice['buyingprice']+(float)$this->extraprice['sendprice']+(float)$this->extraprice['tax']);

			$this->assign('orderpayid',$this->sendinfo['orderpayid']);
			$this->assign('orderpay',$this->sendinfo['orderpay']);
			$this->assign('ordersend',$this->sendinfo['ordersend']);
			$this->assign('sendcomment',$this->sendinfo['sendcomment']);

			$this->assign('cardno',$this->cardinfo['cardno']);
			$this->assign('carddate_year',$this->cardinfo['carddate_year']);
			$this->assign('carddate_month',$this->cardinfo['carddate_month']);

			//=====================閵囧﹤鐪鹃妵鎴濆帥閹稿洤鐣�
			$this->assign('sendname1',$this->addressinfo['sendname1']);
			$this->assign('sendname2',$this->addressinfo['sendname2']);
			//$this->assign('zipcode1',explode('-',$this->addressinfo['zipcode'])[0]);
			$this->assign('zipcode',$this->addressinfo['zipcode'][0].'-'.$this->addressinfo['zipcode'][1]);
			//$this->assign('zipcode2',explode('-',$this->addressinfo['zipcode'])[1]);
			$this->assign('localname',$this->addressinfo['localname']);
			$this->assign('treetname',$this->addressinfo['treetname']);
			$this->assign('address',$this->addressinfo['address']);
			$this->assign('telno',$this->addressinfo['telno'][0].'-'.$this->addressinfo['telno'][1].'-'.$this->addressinfo['telno'][2]);


			//=====================濞夈劍鏋冮懓鍛剰閸拷
			$this->assign('Registersendname1',$this->Registeraddressinfo['sendname1']);
			$this->assign('Registersendname2',$this->Registeraddressinfo['sendname2']);
			//$this->assign('zipcode1',explode('-',$this->addressinfo['zipcode'])[0]);
			$this->assign('Registerzipcode',$this->Registeraddressinfo['zipcode'][0].'-'.$this->Registeraddressinfo['zipcode'][1]);
			//$this->assign('zipcode2',explode('-',$this->addressinfo['zipcode'])[1]);
			$this->assign('Registerlocalname',$this->Registeraddressinfo['localname']);
			$this->assign('Registertreetname',$this->Registeraddressinfo['treetname']);
			$this->assign('Registeraddress',$this->Registeraddressinfo['address']);
			$this->assign('Registertelno',$this->Registeraddressinfo['telno'][0].'-'.$this->Registeraddressinfo['telno'][1].'-'.$this->Registeraddressinfo['telno'][2]);
			$this->assign('Registeremail',$this->Registeraddressinfo['email']);
            
            //$this->assign('newaddress',(isset($this->addressinfo['newaddress'])?$this->addressinfo['newaddress']:""));
		}
		catch(Exception $e)
		{

			echo $e->getMessage();
		}
		$this->_load_php_file("Class_FUNC.php");
		 $site = Class_FUNC::get_site();
	    if(isset($site['site_keyword']))
	    $this->assign('site_keyword', $site['site_keyword']);
        if(isset($site['site_description']))
	    $this->assign('site_description', $site['site_description']);
	    if(isset($site['site_title']))
	    $this->assign('site_title', '確認画面 | ご注文 | 買い物カゴ |'.$site['site_title']);
		
		$this->_load_mdao_class("t_m_goods");
		$goods_dao = new t_m_goods;
		//
		$sql = "SELECT b.id,b.goods_name,b.goods_image,b.goods_unitprice FROM d_good_rank a inner JOIN d_goods b ON a.good_id = b.id ORDER BY a.rank";
		$charts_data = $goods_dao->get_rows($sql);
		foreach ($charts_data as &$value){
			if(isset($value['goods_image']) && !empty($value['goods_image'])){
				$value['goods_image'] = Class_FUNC::get_imagepath($value['id'],$value['goods_image'],1);
			}
		 if(isset($value['goods_unitprice']) && !empty($value['goods_unitprice'])){
	          	 $value['goods_rate'] = $value['goods_unitprice']+$value['goods_unitprice'] * RATE;
	          }
		}
		if (isset($charts_data))
			$this->assign('charts_data',$charts_data);
			
	   $this->assign('pc_meta', $this->fetch('pc/pc_meta.html'));
		$this->assign('chartsing', $this->fetch('pc/charts.html'));
		$this->assign('pc_head', $this->fetch('pc/pc_head.html'));
		$this->assign('pc_foot', $this->fetch('pc/pc_foot.html'));
		$this->display('pc/order_check.html');
	}

	public function saveorder()
	{
		try
		{
			$this->loaduser();
  
			if(!$this->loadsessiondata())
			{
				throw new Exception("no data");
			}
			if(!empty($this->goodslist))
			{
				if($this->datacheck())
				{
             
					if(!empty($this->cardinfo["cardno"]))
                {	require_once("../system/sbps/Class_sbps.php");

					$obj_sbps=new Class_sbps();

					$carddate=$this->cardinfo["carddate_year"].$this->cardinfo["carddate_month"];
					
					$ret=$obj_sbps->trysend($this->cardinfo["cardno"],$carddate);
					if($ret!="")
					{

						//$this->err_mes["msg_txtcard"]=$this->oerr->format_msg($ret);

                        header('Location: pc_Order_temp.html?cerr=1');
                         return;
						//$this->display('pc/order.html');
					}
                    }
					require_once( "../system/Class_M_DAO.php" );
					try {

						$M_dao = new Class_M_DAO;
						/*if($this->Userid!="")
                        {
						$SQL="SELECT
						`id`,
						`user_name1`,
						`user_name2`,
						`user_name_furikana1`,
						`user_name_furikana2`,
						`workshop_name`,
						`workshop_name_furikana`,
						`zipcode`,
						`local_cd`,
						`treet_name`,
						`address`,
						`mobile_number`,
						`email`,
						`tel_number`,
						FROM
						`m_user`
						WHERE id=".$this->Userid."
						;";
						}*/
						$M_dao->begin_trans();

						$neworderid=$this->getneworderid($M_dao);

                        $good_sum=0;
                        foreach($this->goodslist as $goodrow)
						{
                            $good_sum+=($goodrow['goodprice']*$goodrow['goodnum']);
						}
                        
						$SQL="INSERT INTO
								`d_order`
								(
								`user_id`,

								`user_name1`,
								`user_name2`,
								`user_name_f1`,
								`user_name_f2`,
								`user_office_name`,
								`user_office_name_f`,
								`user_zipcode`,
								`user_local_name`,
								`user_treet_name`,
								`user_address`,
								`user_tel_number`,
								`email`,

								`address_name`,
								`send_name1`,
								`send_name2`,
								`send_name_f1`,
								`send_name_f2`,
								`send_office_name`,
								`send_office_name_f`,
								`send_zipcode`,
								`send_local_name`,
								`send_treet_name`,
								`send_address`,
								`send_tel_number`,
								`order_pay_id`,
								`order_pay`,
								`order_send_id`,
								`order_send`,
								`send_comment`,
								`buying_price`,
								`send_price`,
								`tax`,
                                `goods_sum`,
                                `all_sum`,
								`order_number`,
								`order_time`,
								`order_way`,
								`order_status`,
								`order_appraise`,
								`insideappraise`,
								`c_time`,
								`u_time`,
								`c_user`,
								`u_user`
								)
								VALUE (
                                ".($this->Userid!=""?$this->Userid:"-1").",'"
                                .$this->Registeraddressinfo['sendname1']."',
                                '".$this->Registeraddressinfo['sendname2']."',
                                '".$this->Registeraddressinfo['sendnamef1']."',
                                '".$this->Registeraddressinfo['sendnamef2']."',
                                '".$this->Registeraddressinfo['officename']."',
                                '".$this->Registeraddressinfo['officenamef']."',
                                '".$this->Registeraddressinfo['zipcode'][0].'-'.$this->Registeraddressinfo['zipcode'][1]."',
                                '".$this->Registeraddressinfo['localname']."',
                                '".$this->Registeraddressinfo['treetname']."',
                                '".$this->Registeraddressinfo['address']."',
                                '".$this->Registeraddressinfo['telno'][0].'-'.$this->Registeraddressinfo['telno'][1].'-'.$this->Registeraddressinfo['telno'][2]."',
                                '".$this->Registeraddressinfo['email']."',

                                '".$this->addressinfo['address_name']."',
                                '".$this->addressinfo['sendname1']."',
                                '".$this->addressinfo['sendname2']."',
                                '".$this->addressinfo['sendnamef1']."',
                                '".$this->addressinfo['sendnamef2']."',
                                '".$this->addressinfo['officename']."',
                                '".$this->addressinfo['officenamef']."',
                                '".$this->addressinfo['zipcode'][0].'-'.$this->addressinfo['zipcode'][1]."',
                                '".$this->addressinfo['localname']."',
                                '".$this->addressinfo['treetname']."',
                                '".$this->addressinfo['address']."',
                                '".$this->addressinfo['telno'][0].'-'.$this->addressinfo['telno'][1].'-'.$this->addressinfo['telno'][2]."',
                                '".$this->sendinfo['orderpayid']."',
                                '".$this->sendinfo['orderpay']."',
                                '".$this->sendinfo['ordersendid']."',
                                '".$this->sendinfo['ordersend']."',
                                '".$this->sendinfo['sendcomment']."',
                                '".$this->extraprice['buyingprice']."',
                                '".$this->extraprice['sendprice']."',
                                '".$this->extraprice['tax']."',
                                '".$good_sum."',
                                '".($good_sum+$this->extraprice['buyingprice']+$this->extraprice['sendprice']+$this->extraprice['tax'])."',
                                '".$neworderid."',
                                NOW(),
                                '1',
                                '1',
                                '',
                                '',
                                NOW(),
                                NOW(),
                                ".($this->Userid!=""?$this->Userid:"-1").",
                                ".($this->Userid!=""?$this->Userid:"-1")."
                                );";

						if(!$M_dao->exec_sql($SQL))
						{
							throw new Exception("update order error");
						}
						$newID = mysql_insert_id();

						foreach($this->goodslist as $goodrow)
						{
							$SQL="INSERT INTO
									`d_order_goods`
									(
									`good_id`,
									`goods_id`,
									`order_id`,
									`goods_name`,
									`goods_image`,
									`goods_unitprice`,
									`goods_num`,
									`c_time`,
									`u_time`,
									`c_user`,
									`u_user`)
									VALUE (
                                    ".$goodrow['id'].",
                                    '".$goodrow['goodsid']."',
                                    ".$newID.",
                                    '".$goodrow['goodname']."',
                                    '".$goodrow['goodimage']."',
                                    ".$goodrow['goodprice'].",
                                    ".$goodrow['goodnum'].",
                                    NOW(),
                                    NOW(),
                                    ".($this->Userid!=""?$this->Userid:"-1").",
                                    ".($this->Userid!=""?$this->Userid:"-1")."
                                    );";
							if(!$M_dao->exec_sql($SQL))
							{
								throw new Exception("update goodslist error");
							}
						}
						//$M_dao->rollback_trans();

						if($this->sendinfo['orderpayid']=="3")
						{
							//require_once("../system/sbps/Class_sbps.php");

							//$obj_sbps=new Class_sbps();
							$ret=$obj_sbps->sendST01($this->cardinfo['cardno'], $this->cardinfo['carddate_year'].$this->cardinfo['carddate_month'], $neworderid);
							if($ret!="")
							{
								throw new Exception($ret);
								//$this->display('pc/order.html');
							}
							else
							{
								$ret=$obj_sbps->sendST02();
								if($ret!="")
								{
									throw new Exception($ret);
								}
							}
						}

						$this->unlockorderid($M_dao);
                        
                        $this->addnewaddress($M_dao);
                        
						$M_dao->commit_trans();
						$this->clearsessiondata();
					}
					catch(Exception $e)
					{
						$this->unlockorderid($M_dao);
						$M_dao->rollback_trans();
						throw $e;
					}
					header('Location: pc_OrderDone_index.html');
				}
				else
				{
					throw new Exception("check error");

				}
			}

			//$this->display('pc/order_done.html');
		}
		catch(Exception $e)
		{
			//echo $e->getMessage();
			$this->assign('errmsg',$e->getMessage());
			$this->index();
			//$this->display('pc/order_check.html');
		}
    }
    
    public function addnewaddress(&$M_dao)
    {
        if($this->Userid==""){return;}
        if(empty($this->addressinfo['newaddress'])){return;}
        $SQL="INSERT INTO `d_delivery`(
        `login_id`, 
        `sent_name`, 
        `sent_name1`, 
        `sent_name2`, 
        `sent_workshop_name1`, 
        `sent_workshop_name2`, 
        `sent_name_furikana1`, 
        `sent_name_furikana2`, 
        
        `sent_zipcode`, 
        `sent_local_cd`, 
        `sent_treet_name`, 
        `sent_address`, 
        `sent_tel_number`, 
        `c_time`, 
        `u_time`, 
        `c_user`, 
        `u_user`
        ) VALUES (
        (SELECT `login_id` FROM `m_user` WHERE `id`='".$this->Userid."'),
        '".$this->addressinfo['newaddress']."',
        '".$this->addressinfo['sendname1']."',
        '".$this->addressinfo['sendname2']."',
        '".$this->addressinfo['officename']."',
        '".$this->addressinfo['officenamef']."',
        '".$this->addressinfo['sendnamef1']."',
        '".$this->addressinfo['sendnamef2']."',
       
        '".$this->addressinfo['zipcode'][0].'-'.$this->addressinfo['zipcode'][1]."',
        '".$this->addressinfo['local_cd']."',
        '".$this->addressinfo['treetname']."',
        '".$this->addressinfo['address']."',
        '".$this->addressinfo['telno'][0].'-'.$this->addressinfo['telno'][1].'-'.$this->addressinfo['telno'][2]."',
        NOW(),
        NOW(),
        ".$this->Userid.",
        ".$this->Userid."
        )";
      
        if(!$M_dao->exec_sql($SQL))
        {
            throw new Exception("update goodslist error");
        }
        
    }
	public function datacheck()
	{
		//===========

		//============
		return true;
	}

	public function loaduser()
	{
		if(isset($_SESSION['USER']['USER_id']))
		{
			$this->Userid=trim($_SESSION['USER']['USER_id']);
		}
		else
		{
			$this->Userid="";
		}
	}

	public function loadsessiondata()
	{
		if(empty($_SESSION['shopjpgoodslist']))
		{
			return false;
		}

		$this->goodslist=$_SESSION['shopjpgoodslist'];
		$this->extraprice=$_SESSION['shopjpextraprice'];
		$this->sendinfo=$_SESSION['shopjpsendinfo'];
		$this->cardinfo=$_SESSION['shopjpcardinfo'];
		$this->addressinfo=$_SESSION['shopjpaddressinfo'];
		$this->Registeraddressinfo=$_SESSION['shopjpRegisteraddressinfo'];

		/*$this->goodslist=array(array('id'=>111,'goodsid'=>'111','goodname'=>'11111','goodprice'=>100.00,'goodnum'=>'1','goodimage'=>'2.jpg'),array('id'=>112,'goodsid'=>'112','goodname'=>'11112','goodprice'=>200.00,'goodnum'=>'2','goodimage'=>'2.jpg'));
		 $this->extraprice=array('buyingprice'=>10.00,'sendprice'=>20.00,'tax'=>30.00);
		$this->sendinfo=array('orderpayid'=>3,'orderpay'=>'orderpay1','ordersendid'=>0,'ordersend'=>'ordersend1','sendcomment'=>'sendcomment1');
		$this->cardinfo=array('cardno'=>'4123450131003312','carddate_year'=>'2013','carddate_month'=>'09');
		$this->addressinfo=array('address_id'=>'','address_name'=>'addressname1','sendname1'=>'sendname1','sendname2'=>'sendname2','sendnamef1'=>'sendnamef1','sendnamef2'=>'sendnamef2','zipcode'=>explode('-', '111-2222'),'localname'=>'localname1','treetname'=>'treetname1','address'=>'address1','telno'=>explode('-', '999-999-9999'),'officename'=>'officename1','officenamef'=>'officenamef1');
		$this->Registeraddressinfo=array('address_id'=>'','address_name'=>'raddressname1','sendname1'=>'rsendname1','sendname2'=>'rsendname2','sendnamef1'=>'rsendnamef1','sendnamef2'=>'rsendnamef2','zipcode'=>explode('-', '111-2222'),'localname'=>'rlocalname1','treetname'=>'rtreetname1','address'=>'raddress1','telno'=>explode('-', '999-999-9999'),'officename'=>'rofficename1','officenamef'=>'rofficenamef1','email'=>'remail');
		*/
		return true;
	}

	public function clearsessiondata()
	{
        require_once( "../system/Class_Cart.php" );
        Class_Cart::clearCart($this->Userid);
        Class_Cart::clearOtherTemp();
	}

	public function getneworderid(&$M_dao)
	{
		$SQL="select `getOrderNo`() as ono;";
		$orderNo = $M_dao->get_rows($SQL);
		$ono=$orderNo[0]['ono'];
		/*$SQL="LOCK TABLES `m_orderno` WRITE; ";
		 if(!$M_dao->exec_sql($SQL))
			throw new Exception("Lock orderNo error");*/
		return $ono;
	}
	public function unlockorderid(&$M_dao)
	{
		/*$SQL="UNLOCK  TABLES;";
		 if(!$M_dao->exec_sql($SQL))
			throw new Exception("UnLock orderNo error");*/

	}
}